package page

import (
	"context"
	// "fmt"
	"strconv"
	"strings"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/blog/util"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/logic/utils/parse"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/blog/rpc/blogclient"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetPageListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetPageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPageListLogic {
	return &GetPageListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetPageListLogic) GetPageList(req *types.CMSPageListReq) (*types.CMSPageListResp, error) {
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	orderBys := util.ParseSorterNew(req.Sorter)
	filterBys := util.ParseFilterNew(req.Filter, req.Type)

	var ids *string
	var search *string
	if req.Search != nil && len(strings.TrimSpace(*req.Search)) > 0 { // 前端可以搜名称或者ID
		reqSearch := strings.TrimSpace(*req.Search)
		if _, err := strconv.ParseInt(reqSearch, 10, 64); err == nil {
			ids = pointy.GetPointer(reqSearch)
		} else {
			search = pointy.GetPointer(reqSearch)
		}
	}

	if req.Id != nil && *req.Id > 0 {
		ids = pointy.GetPointer(strconv.FormatUint(*req.Id, 10))
	}
	if req.PageIds != nil && len(strings.TrimSpace(*req.PageIds)) > 0 {
		ids = pointy.GetPointer(strings.TrimSpace(*req.PageIds))
	}

	data, err := l.svcCtx.BlogRpc.BackendGetPageList(l.ctx, &blogclient.PageListReq{
		Page:        page,
		PageSize:    pageSize,
		Ids:         ids,
		Title:       req.Title,
		Slug:        req.Slug,
		Excerpt:     req.Excerpt,
		Search:      search,
		AuthorId:    req.AuthorId,
		Status:      req.Status,
		StartTime:   req.StartTime,
		EndTime:     req.EndTime,
		OrderBy:     orderBys,
		FilterBy:    filterBys,
		WithMeta:    req.WithMeta,
		WithMedia:   req.WithMedia,
		WithTag:     req.WithTag,
		WithContent: req.WithContent,
	})
	if err != nil {
		return nil, err
	}

	resp := &types.CMSPageListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.CMSPageListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
			StatusStatisticMap: data.StatusStatisticMap,
		},
	}

	for _, v := range data.List {
		var meta []*types.MetaInfo
		var media []*types.MediaInfo
		var categories []*types.CMSTermInfo
		var tags []*types.CMSTermInfo

		var photoCount *uint32
		var viewCount *uint32
		var forwardCount *uint32
		var pendingStatus *uint32
		if len(v.Meta) > 0 {
			for _, m := range v.Meta {
				if m.Key != nil && m.Value != nil {
					switch *m.Key {
					case "photoCount":
						if i, err := strconv.ParseInt(*m.Value, 10, 32); err == nil {
							photoCount = pointy.GetPointer(uint32(i))
						}
					case "viewCount":
						if i, err := strconv.ParseInt(*m.Value, 10, 32); err == nil {
							viewCount = pointy.GetPointer(uint32(i))
						}
					case "forwardCount":
						if i, err := strconv.ParseInt(*m.Value, 10, 32); err == nil {
							forwardCount = pointy.GetPointer(uint32(i))
						}
					case "pendingStatus":
						if i, err := strconv.ParseInt(*m.Value, 10, 32); err == nil {
							pendingStatus = pointy.GetPointer(uint32(i))
						}
					default:
						meta = append(meta, &types.MetaInfo{
							Id:    m.Id,
							Key:   m.Key,
							Value: m.Value,
						})
					}
				}
			}
		}

		if len(v.Media) > 0 {
			for _, m := range v.Media {
				var url string
				if m.Url != nil && len(*m.Url) > 0 {
					url = *m.Url
				}
				if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
					url = *m.Uri
				}
				filename, mimeType, metaData := utils.ParseMetaData(m.MetaData)
				media = append(media, &types.MediaInfo{
					Uid:       m.Uid,
					Id:        m.Id,
					Thumbnail: m.Thumbnail,
					Order:     m.Order,
					Url:       pointy.GetPointer(url),
					Name:      pointy.GetPointer(filename),
					MimeType:  pointy.GetPointer(mimeType),
					AltText:   m.AltText,
					MetaData:  pointy.GetPointer(metaData),
				})
			}
		}

		if len(v.Categories) > 0 {
			for _, m := range v.Categories {
				categories = append(categories, &types.CMSTermInfo{
					BaseIDInfo: types.BaseIDInfo{
						Id: m.Id,
					},
					Name: m.Name,
					Slug: m.Slug,
				})
			}
		}

		if len(v.Tags) > 0 {
			for _, m := range v.Tags {
				tags = append(tags, &types.CMSTermInfo{
					BaseIDInfo: types.BaseIDInfo{
						Id: m.Id,
					},
					Name: m.Name,
					Slug: m.Slug,
				})
			}
		}

		option := util.GetAuditOptionByStatus(v.Status)
		var uri *string
		if v.Uri != nil && len(*v.Uri) > 0 {
			if strings.HasPrefix(*v.Uri, l.svcCtx.Config.NfsConf.SiteUrl) {
				uri = v.Uri
			} else {
				uri = pointy.GetPointer(l.svcCtx.Config.NfsConf.SiteUrl + *v.Uri)
			}
		}

		resp.Data.List = append(resp.Data.List, &types.CMSPageInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:         v.Id,
				CreatedAt:  v.CreatedAt,
				UpdatedAt:  v.UpdatedAt,
				DeletedAt:  v.DeletedAt,
				CanAccept:  option.CanAccept,
				CanReject:  option.CanReject,
				CanRemove:  option.CanRemove,
				CanRestore: option.CanRestore,
			},
			Title:         v.Title,
			Slug:          v.Slug,
			Content:       v.ContentFiltered,
			ContentHtml:   v.Content,
			Excerpt:       v.Excerpt,
			ParentId:      v.ParentId,
			AuthorId:      v.AuthorId,
			Status:        v.Status,
			PendingStatus: pendingStatus,
			CommentStatus: v.CommentStatus,
			Sort:          v.Sort,
			Visibility:    v.Visibility,
			Password:      v.Password,
			Uri:           uri,
			PhotoCount:    photoCount,
			ViewCount:     viewCount,
			ForwardCount:  forwardCount,
			CommentCount:  v.CommentCount,
			CanSubmit:     option.CanSubmit,

			Meta:       meta,
			Media:      media,
			Categories: categories,
			Tags:       tags,
		})
	}

	return resp, nil
}
